import "./App.css";

import Header from "./components/Header/Header";
import List from "./components/List/List";
import { useState } from "react";

function App() {
  const [todoList, setTodoList] = useState([]);

  const setTodoHandler = (todoItem) => {
    const newTodoList = [...todoList, todoItem];
    setTodoList(newTodoList);
  };

  const deleteHandler = (id) => {
    const newTodoList = JSON.parse(JSON.stringify(todoList));
    const idx = newTodoList.findIndex((item) => item.id === id);
    newTodoList.splice(idx, 1);
    setTodoList(newTodoList);
  };

  const updateHandler = (id, complete) => {
    const idx = todoList.findIndex((item) => item.id === id);
    const newTodoList = JSON.parse(JSON.stringify(todoList));
    const newTodo = {
      ...newTodoList[idx],
      complete: !newTodoList[idx].complete,
    };
    newTodoList.splice(idx, 1, newTodo);
    setTodoList(newTodoList);
  };

  return (
    <div className="App">
      <Header setTodoList={setTodoHandler} />
      <List
        delete={deleteHandler}
        deleteHandler={deleteHandler}
        updateHandler={updateHandler}
        todoList={todoList}
      />
    </div>
  );
}

export default App;
